package http

import (
	"gitee.com/saxon134/sysmain/conf"
	"gitee.com/saxon134/sysmain/controller"
	"github.com/saxon134/go-utils/saData/saUrl"
	"github.com/saxon134/go-utils/saLog"
	"net/http"
)

// Init 阻塞
func Init() {
	if conf.Conf.Http.Port == "" {
		panic("http port can not be empty")
	}

	addHandle("", controller.Index)

	//账户
	addHandle("account/menus", controller.AccountMenus)
	addHandle("account/login", controller.AccountLogin)
	addHandle("account/save", controller.AccountSave)

	//SDP
	addHandle("sdp/register", controller.SdpRegisterHandler)
	addHandle("sdp/ping", controller.SdpPingHandler)
	addHandle("sdp/discovery", controller.SdpDiscoveryHandler)

	//Task
	addHandle("task/register", controller.TaskRegisterHandler)
	addHandle("task/save", controller.TaskSaveHandler)
	addHandle("task/run", controller.TaskRunHandler)
	addHandle("task/status", controller.TaskRunStatus)
	addHandle("task/list", controller.TaskListHandler)
	addHandle("task/record/list", controller.TaskRecordsHandler)
	addHandle("task/record/add", controller.TaskAddRecordHandler)

	//应用
	addHandle("app/list", controller.AppList)
	addHandle("host/list", controller.HostList)

	//stats 接口调用情况
	addHandle("api/overview", controller.ApiOverview)
	addHandle("api/list", controller.ApiList)
	addHandle("api/intervals", controller.ApiIntervalList)

	//资源服务器
	addHandle("resource", controller.GetResources)
	addHandle("resource/sync/ecs/list", controller.SyncAliyunEcsList)
	addHandle("resource/sync/ecs/monitor", controller.SyncAliyunEcsMonitor)

	saLog.Log("Http listening on " + conf.Conf.Http.Port)
	err := http.ListenAndServe(":"+conf.Conf.Http.Port, nil)
	if err != nil {
		panic("http err:" + err.Error())
	}
}

func addHandle(path string, h func(http.ResponseWriter, *http.Request)) {
	http.HandleFunc(saUrl.ConnPath(conf.Conf.Http.Root, path), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, timestamp, sign")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		if r.Method == "OPTIONS" {
			w.WriteHeader(200)
			_, _ = w.Write([]byte("ok"))
			return
		}
		h(w, r)
	})
}
